/**
 * 
 */

package com.trydofor.id.test;

/**
 * @author : Shi Rongjiu (www.trydofor.com)
 */
public abstract class NanoMarker {
    
    public static Report reportSpeed(String name, Runnable run, long nano) {
        long costs = 0;
        long loops = 0;
        long start = System.nanoTime();
        while (true) {
            costs = System.nanoTime() - start;
            if (costs >= nano) {
                break;
            }
            else {
                run.run();
                loops++;
            }
        }
        
        return new Report(name,loops,costs);
    }
    
    public static class Report {
        
        String name;
        long   loops;
        long   costs;
        
        public Report(String name, long loops, long costs) {
            super();
            this.name = name;
            this.loops = loops;
            this.costs = costs;
        }

        public String getName() {
            return name;
        }
        
        public long getLoops() {
            return loops;
        }
        
        public long getCosts() {
            return costs;
        }
        
        public long getSpeed() {
            return costs / loops;
        }
        
        public static String getHeader(){
            return "\tSPEED\tLOOPS\tCOSTS\tNAME";
        }
        
        public String toString(){
            StringBuilder sb = new StringBuilder();
            sb.append("\t");
            sb.append(getSpeed());
            sb.append("\t");
            sb.append(loops);
            sb.append("\t");
            sb.append(costs);
            sb.append("\t");
            sb.append(name);
            
            return sb.toString();
        }
    }
}
